package com.visionork.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.visionork.rss.Message;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ShowActivity extends ListActivity {
	private class ShowVideo {
		public int index;
		public String youtubeID;
		public String title;
	}

	public static final String url_key = "URL";
	public static final String title_key = "TITLE";
	private String _title;
	private String _url;
	private ArrayList<ShowVideo> showVideoList;
	private Activity _thisActivity;
	ArrayList<String> titles = new ArrayList<String>();
	private ProgressDialog pd;
	private Handler handler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		_title = getIntent().getStringExtra(title_key);
		_url = getIntent().getStringExtra(url_key);
		_thisActivity = this;
		handler = new Handler();
		
		pd = ProgressDialog.show(this, "Loaing...", "Load Video List", true,
				false);
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				loadShowList();
				handler.post(new Runnable() {
					@Override
					public void run() {
						ArrayAdapter<String> adapter = new ArrayAdapter<String>(
								_thisActivity, R.layout.row, titles);

						setListAdapter(adapter);
						pd.dismiss();
					}
				});
			}

		};
		new Thread(runnable).start();
	}

	@Override
	public void onStart() {
		super.onStart();
				
	}

	/*
	 * private Handler handler = new Handler() { public void
	 * handleMessage(Message msg) { pd.dismiss();
	 * 
	 * Toast.makeText(getApplicationContext(), "Load Video List Done",
	 * Toast.LENGTH_SHORT).show();
	 * 
	 * ArrayAdapter<String> adapter = new ArrayAdapter<String>( _thisActivity,
	 * R.layout.row, titles);
	 * 
	 * setListAdapter(adapter);
	 * 
	 * } };
	 */

	private void loadShowList() {
		showVideoList = new ArrayList<ShowVideo>();

		// Add Default One
		String defaultYId = getYoutubeID(_url);
		ShowVideo defaultVideo = new ShowVideo();
		defaultVideo.index = 1;
		defaultVideo.youtubeID = defaultYId;
		defaultVideo.title = "Part 1";
		titles.add(defaultVideo.title);

		showVideoList.add(defaultVideo);
		String preId = defaultVideo.youtubeID;
		int i = 2;
		while (true) {
			String url = _url + i;

			String yId = null;
			try {
				yId = getYoutubeID(url);
				if (preId.compareTo(yId) != 0) {
					preId = yId;
					ShowVideo videoRecord = new ShowVideo();
					videoRecord.index = i;
					videoRecord.youtubeID = yId;
					videoRecord.title = "Part " + i;
					titles.add(videoRecord.title);
					showVideoList.add(videoRecord);
				} else {
					break;
				}
			} catch (RuntimeException e) {
				Log.i("Exception", e.getClass().getName());
				break;
			}
			i++;
		}
		/*
		 * ArrayAdapter<String> adapter = new
		 * ArrayAdapter<String>(_thisActivity, R.layout.row, titles);
		 * 
		 * setListAdapter(adapter);
		 */
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		String yId = showVideoList.get(position).youtubeID;
		playYoutubeVideo(yId);
	}

	private void playYoutubeVideo(String videoID) {
		Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"
				+ videoID));
		startActivity(i);
	}

	private String getYoutubeID(String urlString) {
		String id = null;
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e) { // TODO Auto-generated catch block
			e.printStackTrace();
		}
		InputStream ins = null;
		try {
			ins = url.openStream();
		} catch (IOException e) { // TODO Auto-generated
			e.printStackTrace();
		}

		Scanner s = new Scanner(ins);
		while (s.hasNextLine()) {
			String line = s.nextLine();
			Pattern r = Pattern
					.compile("http://www.youtube.com/v/([^\\?]*)\\?");
			Matcher m = r.matcher(line);
			if (m.find()) {
				id = m.group(1);
				break;
			}
		}
		s.close();

		return id;
	}
}
